package com.ithinkstudio.jeez.service.impl;

import com.ithinkstudio.jeez.dao.IUserMapper;
import com.ithinkstudio.jeez.dao.jpa.IUserRepository;
import com.ithinkstudio.jeez.entity.User;
import com.ithinkstudio.jeez.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @program: springboot-mybatis
 * @description: 用户服务层
 * @author: fengzp
 * @create: 2020/04/14
 */
@Service
public class UserService implements IUserService {

    @Resource
    private IUserMapper userMapper;

    @Resource
    private IUserRepository userRepository;

    /**
     * 根据ID查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    public void insertUser(User user) {
        userMapper.insert(user);
    }

    /**
     * 更新用户
     *
     * @param user
     */
    @Override
    public void updateUser(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Integer id) {
        User user = userRepository.findById(id).get();
        user.setSalt("Mybatis update");
        user.setName(null);
        this.userMapper.updateByPrimaryKeySelective(user);

        user.setName("JPA update");
        userRepository.save(user);
        //throw new RuntimeException("事务测试");
    }


}
